/*
 * This program is free software: you can redistribute it and/or modify it under
 * the terms of the GNU General Public License as published by the Free Software
 * Foundation, either version 3 of the License, or (at your option) any later
 * version.
 * 
 * This program is distributed in the hope that it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
 * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
 * details.
 * 
 * You should have received a copy of the GNU General Public License along with
 * this program. If not, see <http://www.gnu.org/licenses/>.
 */
package jmmos.gameserver.network.clientpackets;

import jmmos.gameserver.datatables.GuildTable;
import jmmos.gameserver.instancemanager.CastleManager;
import jmmos.gameserver.model.MMOGuild;
import jmmos.gameserver.model.actor.instance.MMOPcInstance;
import jmmos.gameserver.model.entity.Castle;
import jmmos.gameserver.network.serverpackets.SiegeDefenderList;

/**
 * This class ...
 * @version $Revision: 1.3.4.2 $ $Date: 2005/03/27 15:29:30 $
 */
public final class RequestConfirmSiegeWaitingList extends MMOGameClientPacket
{
	private static final String _C__AE_RequestConfirmSiegeWaitingList = "[C] AE RequestConfirmSiegeWaitingList";
	
	private int _approved;
	private int _castleId;
	private int _guildId;
	
	@Override
	protected void readImpl()
	{
		_castleId = readD();
		_guildId = readD();
		_approved = readD();
	}
	
	@Override
	protected void runImpl()
	{
		MMOPcInstance activeChar = getClient().getActiveChar();
		if (activeChar == null)
		{
			return;
		}
		
		// Check if the player has a guild
		if (activeChar.getGuild() == null)
		{
			return;
		}
		
		Castle castle = CastleManager.getInstance().getCastleById(_castleId);
		if (castle == null)
		{
			return;
		}
		
		// Check if leader of the guild who owns the castle?
		if ((castle.getOwnerId() != activeChar.getGuildId()) || (!activeChar.isGuildLeader()))
		{
			return;
		}
		
		MMOGuild guild = GuildTable.getInstance().getGuild(_guildId);
		if (guild == null)
		{
			return;
		}
		
		if (!castle.getSiege().getIsRegistrationOver())
		{
			if (_approved == 1)
			{
				if (castle.getSiege().checkIsDefenderWaiting(guild))
				{
					castle.getSiege().approveSiegeDefenderGuild(_guildId);
				}
				else
				{
					return;
				}
			}
			else
			{
				if ((castle.getSiege().checkIsDefenderWaiting(guild)) || (castle.getSiege().checkIsDefender(guild)))
				{
					castle.getSiege().removeSiegeGuild(_guildId);
				}
			}
		}
		
		// Update the defender list
		activeChar.sendPacket(new SiegeDefenderList(castle));
		
	}
	
	@Override
	public String getType()
	{
		return _C__AE_RequestConfirmSiegeWaitingList;
	}
}
